package com.github.byakkili.bim.protocol.json2protobuf.tcp;

import com.github.byakkili.bim.core.BimSession;
import com.github.byakkili.bim.core.handler.command.CommandFrame;
import com.github.byakkili.bim.core.support.util.BimSessionUtils;
import com.github.byakkili.bim.protocol.json2protobuf.BaseJson2protoBufCodec;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author Guannian Li
 */
@Sharable
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TcpJson2protoBufCodec extends BaseJson2protoBufCodec<ByteBuf> {
    /**
     * 单例
     */
    public static final TcpJson2protoBufCodec INSTANCE = new TcpJson2protoBufCodec();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        BimSession session = BimSessionUtils.get(ctx.channel());

        int command = byteBuf.readInt();
        byte[] bytes = ByteBufUtil.getBytes(byteBuf);
        String jsonStr = new String(bytes, StandardCharsets.UTF_8);

        CommandFrame frame = convertCommandFrame(session, command, jsonStr);
        out.add(frame);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, CommandFrame<Message> frame, List<Object> out) throws Exception {
        TcpJsonToProtoBufPacket packet = new TcpJsonToProtoBufPacket(frame);
        byte[] bytes = packet.toByteArray();

        out.add(Unpooled.wrappedBuffer(bytes));
    }
}